<template>
  <div class="org-center">
    <el-tabs v-model="activeListTab" class="org-center__tabs">
      <el-tab-pane label="组织列表" name="org">
        <el-row :gutter="16">
          <el-col :span="organizationDrawerVisible ? 10 : 24">
            <el-card shadow="never" class="org-center__panel">
              <template #header>
                <div class="flex items-center justify-between">
                  <span class="text-base font-medium">组织列表</span>
                  <el-button type="primary" :icon="useRenderIcon('ep:plus')" @click="openCreateOrganization">
                    新增组织
                  </el-button>
                </div>
              </template>

              <OrganizationFilter
                :loading="orgLoading"
                :filter-form="orgFilter"
                :regions="regionTree"
                @search="handleOrgSearch"
                @reset="handleOrgReset"
              />

              <PureTableBar
                title="组织列表"
                :columns="orgColumns"
                :tableRef="orgTableRef"
                @refresh="handleOrgSearch"
                @fullscreen="orgTableRef.value?.setAdaptive?.()"
              >
                <template #default="{ size, dynamicColumns }">
                  <PureTable
                    ref="orgTableRef"
                    v-loading="orgLoading"
                    row-key="id"
                    :columns="dynamicColumns"
                    :data="orgList"
                    :size="size"
                    :pagination="orgPagination"
                    adaptive
                    :adaptiveConfig="{ offsetBottom: organizationDrawerVisible ? 24 : 56 }"
                    @row-click="handleOrgRowClick"
                    @page-size-change="handleOrgPageSizeChange"
                    @page-current-change="handleOrgPageChange"
                  >
                    <template #org_type="{ row }">
                      {{ row.org_type_label || row.org_type || "-" }}
                    </template>
                    <template #status="{ row }">
                      <el-tag :type="statusTagType(row.status)" size="small" effect="plain">
                        {{ row.status_label || "-" }}
                      </el-tag>
                    </template>
                    <template #region="{ row }">
                      {{ row.region_label || row.region?.name || "-" }}
                    </template>
                    <template #operation="{ row }">
                      <el-space>
                        <el-button
                          link
                          type="primary"
                          :icon="useRenderIcon('ep:view')"
                          @click="selectOrganization(row)"
                        >
                          详情
                        </el-button>
                        <el-button
                          link
                          type="primary"
                          :icon="useRenderIcon('ep:edit')"
                          @click="openEditOrganization(row)"
                        >
                          编辑
                        </el-button>
                        <el-button
                          link
                          type="danger"
                          :icon="useRenderIcon('ep:delete')"
                          @click="removeOrganization(row)"
                        >
                          删除
                        </el-button>
                      </el-space>
                    </template>
                  </PureTable>
                </template>
              </PureTableBar>
            </el-card>
          </el-col>

          <transition name="el-fade-in-linear">
            <el-col v-if="organizationDrawerVisible" :span="14">
              <el-card shadow="never" class="org-center__panel org-center__panel--detail">
                <template #header>
                  <div class="flex items-center justify-between">
                    <div class="flex items-center">
                      <el-button link type="primary" :icon="useRenderIcon('ep:back')" @click="closeOrganizationDetail">
                        返回列表
                      </el-button>
                      <span class="ml-2 text-base font-medium">{{ currentOrganization?.name || "组织详情" }}</span>
                      <el-tag v-if="currentOrganization" class="ml-2" size="small" effect="plain">
                        ID: {{ currentOrganization.id }}
                      </el-tag>
                    </div>
                    <el-space>
                      <el-button type="primary" :icon="useRenderIcon('ep:edit')" @click="openEditOrganization(currentOrganization)">
                        编辑
                      </el-button>
                      <el-button type="danger" :icon="useRenderIcon('ep:delete')" @click="removeOrganization(currentOrganization)">
                        删除
                      </el-button>
                    </el-space>
                  </div>
                </template>

                <el-tabs v-model="activeDetailTab">
                  <el-tab-pane name="profile" label="组织资料">
                    <OrganizationProfile :organization="currentOrganization" :loading="orgLoading" />
                  </el-tab-pane>
                  <el-tab-pane name="members" label="成员列表">
                    <OrganizationMembers
                      v-if="currentOrganization"
                      :organization="currentOrganization"
                      :loading="membersLoading"
                      :pagination="memberPagination"
                      :columns="memberColumns"
                      :table-data="memberList"
                      @refresh="loadMembers"
                      @page-change="handleMemberPageChange"
                      @page-size-change="handleMemberPageSizeChange"
                      @create="openMemberDialog"
                      @edit="openMemberDialog"
                      @remove="deleteMember"
                    />
                  </el-tab-pane>
                  <el-tab-pane name="audit" label="审核记录">
                    <OrganizationAudit
                      v-if="currentOrganization"
                      :organization="currentOrganization"
                      :records="auditRecords"
                      :loading="auditRecordsLoading"
                      @refresh="loadAuditRecords"
                      @approve="handleAuditApprove"
                      @reject="handleAuditReject"
                      @fast-create="openQuickCreate"
                    />
                  </el-tab-pane>
                </el-tabs>
              </el-card>
            </el-col>
          </transition>
        </el-row>
      </el-tab-pane>

      <el-tab-pane label="待审核企业" name="audit">
        <el-card shadow="never" class="org-center__panel">
          <template #header>
            <div class="flex items-center justify-between">
              <span class="text-base font-medium">待审核企业</span>
              <el-button text type="primary" :icon="useRenderIcon('ep:refresh')" @click="handleAuditSearch">
                刷新
              </el-button>
            </div>
          </template>

          <el-form
            :inline="true"
            :model="auditFilter"
            class="search-form bg-bg_color w-full pl-4 pt-3 pb-2 overflow-auto"
          >
            <el-form-item label="关键词：" prop="keyword">
              <el-input
                v-model="auditFilter.keyword"
                placeholder="企业名称 / 联系方式"
                clearable
                class="w-[220px]!"
              />
            </el-form-item>
            <el-form-item label="区域：" prop="region_id">
              <el-select
                v-model="auditFilter.region_id"
                placeholder="全部区域"
                clearable
                filterable
                class="w-[220px]!"
              >
                <el-option label="全部区域" value="" />
                <el-option
                  v-for="option in flatRegionOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-space>
                <el-button type="primary" :icon="useRenderIcon('ep:search')" @click="handleAuditSearch">
                  查询
                </el-button>
                <el-button :icon="useRenderIcon('ep:refresh')" @click="handleAuditReset">
                  重置
                </el-button>
              </el-space>
            </el-form-item>
          </el-form>

          <PureTableBar
            title="待审核企业"
            :columns="auditColumns"
            :tableRef="auditTableRef"
            @refresh="handleAuditSearch"
            @fullscreen="auditTableRef.value?.setAdaptive?.()"
          >
            <template #default="{ size, dynamicColumns }">
              <PureTable
                ref="auditTableRef"
                v-loading="auditPendingLoading"
                row-key="audit_id"
                :columns="dynamicColumns"
                :data="auditList"
                :size="size"
                :pagination="auditPagination"
                adaptive
                :adaptiveConfig="{ offsetBottom: 56 }"
                @page-size-change="handleAuditPageSizeChange"
                @page-current-change="handleAuditPageChange"
              >
                <template #inviter="{ row }">
                  <span>
                    {{
                      row.inviter?.nickname ||
                      row.inviter?.real_name ||
                      row.inviter?.phone ||
                      row.invited_by ||
                      "-"
                    }}
                  </span>
                </template>
                <template #region="{ row }">
                  {{ row.region?.path || row.region?.name || "-" }}
                </template>
                <template #audit_status="{ row }">
                  <el-tag :type="auditStatusTagType(row.status)" size="small" effect="plain">
                    {{ row.status_label || "-" }}
                  </el-tag>
                </template>
                <template #audit_operation="{ row }">
                  <el-space>
                    <el-button
                      link
                      type="primary"
                      :icon="useRenderIcon('ep:view')"
                      @click="openAuditDetail(row)"
                    >
                      详情
                    </el-button>
                    <el-button
                      link
                      type="primary"
                      :icon="useRenderIcon('ep:circle-check')"
                      @click="approveAuditRecord(row)"
                    >
                      通过
                    </el-button>
                    <el-button
                      link
                      type="danger"
                      :icon="useRenderIcon('ep:circle-close')"
                      @click="rejectAuditRecord(row)"
                    >
                      驳回
                    </el-button>
                  </el-space>
                </template>
              </PureTable>
            </template>
          </PureTableBar>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <OrganizationModal
      v-model:visible="organizationModalVisible"
      :organization="editingOrganization"
      :mode="organizationModalMode"
      @success="handleOrganizationModalSuccess"
    />

    <MemberModal
      v-model:visible="memberModalVisible"
      :organization="currentOrganization"
      :member="editingMember"
      :mode="memberModalMode"
      @success="handleMemberModalSuccess"
    />

    <QuickCreateDrawer
      v-model:visible="quickCreateVisible"
      :regions="regionTree"
      @success="handleQuickCreateSuccess"
    />

    <el-drawer
      v-model="auditDetailVisible"
      title="待审核企业详情"
      size="520px"
      destroy-on-close
      @close="closeAuditDetail"
    >
      <template v-if="selectedAuditRecord">
        <el-descriptions :column="1" border class="mb-4">
          <el-descriptions-item label="企业名称">
            {{ selectedAuditRecord.display_name || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="统一社会信用代码">
            {{ selectedAuditRecord.company?.license_code || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="法人代表">
            {{ selectedAuditRecord.company?.legal_rep || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="注册地址">
            {{ selectedAuditRecord.company?.address || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="经营范围">
            {{ selectedAuditRecord.company?.scope || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="提交时间">
            {{ selectedAuditRecord.submitted_at || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="邀请人">
            {{
              selectedAuditRecord.inviter?.nickname ||
              selectedAuditRecord.inviter?.real_name ||
              selectedAuditRecord.inviter?.phone ||
              selectedAuditRecord.invited_by ||
              "-"
            }}
          </el-descriptions-item>
          <el-descriptions-item label="所属区域">
            {{ selectedAuditRecord.region?.path || selectedAuditRecord.region?.name || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="auditStatusTagType(selectedAuditRecord.status)" size="small" effect="plain">
              {{ selectedAuditRecord.status_label || "-" }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <el-divider>联系与票据</el-divider>
        <el-descriptions :column="1" border class="mb-4">
          <el-descriptions-item label="开票抬头">
            {{
              selectedAuditRecord.company?.invoice?.invoice_title ||
              selectedAuditRecord.company?.company_name ||
              "-"
            }}
          </el-descriptions-item>
          <el-descriptions-item label="纳税识别号">
            {{ selectedAuditRecord.company?.invoice?.invoice_taxno || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="开票联系人">
            {{ selectedAuditRecord.company?.invoice?.contact_name || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ selectedAuditRecord.company?.invoice?.contact_phone || selectedAuditRecord.phone || "-" }}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider>地址信息</el-divider>
        <el-empty
          v-if="!selectedAuditRecord.company?.addresses?.length"
          description="暂无地址信息"
        />
        <el-timeline v-else class="mb-4">
          <el-timeline-item
            v-for="(address, index) in selectedAuditRecord.company?.addresses || []"
            :key="index"
            :timestamp="address.address_type === 'billing' ? '开票地址' : '收货地址'"
            placement="top"
          >
            <div class="text-sm text-gray-600">
              <p>
                {{ address.province || "-" }} {{ address.city || "" }} {{ address.district || "" }}
              </p>
              <p>{{ address.address || "-" }}</p>
              <p>
                联系人：{{ address.contact_name || "-" }}
                <span class="ml-2">电话：{{ address.contact_phone || "-" }}</span>
                <span v-if="Number(address.is_default) === 1" class="ml-2">
                  <el-tag size="small" type="success" effect="plain">默认</el-tag>
                </span>
              </p>
            </div>
          </el-timeline-item>
        </el-timeline>

        <div class="drawer-footer">
          <el-button type="primary" :icon="useRenderIcon('ep:circle-check')" @click="approveAuditRecord(selectedAuditRecord)">
            通过
          </el-button>
          <el-button type="danger" :icon="useRenderIcon('ep:circle-close')" @click="rejectAuditRecord(selectedAuditRecord)">
            驳回
          </el-button>
        </div>
      </template>
      <el-empty v-else description="请选择待审核企业" />
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { PureTableBar } from "@/components/RePureTableBar";
import OrganizationFilter from "./components/OrganizationFilter.vue";
import OrganizationProfile from "./components/OrganizationProfile.vue";
import OrganizationMembers from "./components/OrganizationMembers.vue";
import OrganizationAudit from "./components/OrganizationAudit.vue";
import OrganizationModal from "./components/OrganizationModal.vue";
import MemberModal from "./components/MemberModal.vue";
import QuickCreateDrawer from "./components/QuickCreateDrawer.vue";
import { useOrganizationCenter } from "./hooks/useOrganizationCenter";

defineOptions({ name: "OrganizationCenter" });

const {
  activeListTab,
  orgTableRef,
  auditTableRef,
  regionTree,
  orgFilter,
  orgColumns,
  orgList,
  orgLoading,
  orgPagination,
  handleOrgSearch,
  handleOrgReset,
  handleOrgRowClick,
  handleOrgPageChange,
  handleOrgPageSizeChange,
  selectOrganization,
  organizationDrawerVisible,
  currentOrganization,
  closeOrganizationDetail,
  statusTagType,
  openCreateOrganization,
  openEditOrganization,
  removeOrganization,
  organizationModalVisible,
  organizationModalMode,
  editingOrganization,
  handleOrganizationModalSuccess,
  membersLoading,
  memberColumns,
  memberList,
  memberPagination,
  loadMembers,
  handleMemberPageChange,
  handleMemberPageSizeChange,
  openMemberDialog,
  deleteMember,
  memberModalVisible,
  memberModalMode,
  editingMember,
  handleMemberModalSuccess,
  auditPendingLoading,
  auditRecordsLoading,
  auditRecords,
  loadAuditRecords,
  handleAuditApprove,
  handleAuditReject,
  quickCreateVisible,
  handleQuickCreateSuccess,
  openQuickCreate,
  auditFilter,
  auditColumns,
  auditList,
  auditPagination,
  flatRegionOptions,
  handleAuditSearch,
  handleAuditReset,
  handleAuditPageChange,
  handleAuditPageSizeChange,
  auditStatusTagType,
  auditDetailVisible,
  selectedAuditRecord,
  openAuditDetail,
  closeAuditDetail,
  approveAuditRecord,
  rejectAuditRecord
} = useOrganizationCenter();

const activeDetailTab = ref("profile");

watch(currentOrganization, val => {
  if (!val) {
    activeDetailTab.value = "profile";
  }
});
</script>

<style scoped>
.org-center {
  padding: 12px;
}

.org-center__tabs {
  width: 100%;
}

.org-center__panel {
  margin-bottom: 16px;
}

.org-center__panel--detail {
  min-height: calc(100vh - 120px);
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
